app.controller('advancedSearchController', ['$scope', "$rootScope",'$state', '$stateParams', '$http', 'ControllerConfig','$translate','$compile',
    function ($scope,$rootScope, $state, $stateParams, $http, ControllerConfig,$translate,$compile) {

        $scope.$on('$viewContentLoaded', function (event) {
            $http({
                method : 'GET',
                url : "/Portal/Organization/GetCurrentUser",
            }).success(function(result) {
                //debugger;
                $scope.currentUser = result.User;
                $scope.departName = result.OUDepartName;
            })
            $scope.init();
        });




        $scope.logicalCondition="";




      //  $scope.baseSql= "SELECT distinct a.documentName,a.trade,a.product,a.spareParts,a.formingMethod,a.brandName,b.FinishTime,b.OriginatorName,b.Originator,b.ObjectID as instanceId from i_knowledge a INNER JOIN ot_instancecontext b on a.ObjectID = b.BizObjectId left join i_materialtrait c on c.ParentObjectID=a.ObjectID  where 1=1 ";
        $scope.baseSql="";
        $scope.knowledgeMapping=[];
        $scope.knowledgeChildMapping=[];
        $scope.dataRepository=[];
        $scope.tableMark = 0 ;
        $scope.tableChildMark = 0 ;
        $scope.init = function() {
            $http({
                method : 'GET',
                url : "/Portal/kumhosunny/viewdata/knowledgeDataMapping",
            }).success(function(result) {
                $scope.knowledgeMapping=result.listParent;
                $scope.knowledgeChildMapping=result.listChild;
            })

            $http({
                method : 'GET',
                url : "/Portal/kumhosunny/viewdata/getDataRepository",
            }).success(function(result) {
                $scope.dataRepository=result;
            })


            $http({
                method : 'GET',
                url : "/Portal/kumhosunny/viewdata/getKnowledegeSql",
            }).success(function(result) {
                var base = new Base64();
                $scope.baseSql= base.decode(result.baseSqlEncoder);
            })


            if(localStorage.getItem('localCondition')!="" && localStorage.getItem('localCondition')!=null && localStorage.getItem('localCondition')!=undefined){
                $scope.logicalCondition= eval(localStorage.getItem('localCondition'));
                setTimeout( function(){
                    $scope.$apply(function () {
                         $scope.logicalCondition=  $scope.logicalCondition;

                    });

                },6000);
            }else{

                $scope.logicalCondition=
                    [
                        {
                         "andOr":"UNION",
                         "table":
                            [
                                {
                                    "field": "",
                                    "mappingType": "",
                                    "type": "",
                                    "fieldValue": "",
                                    "minValue": "",
                                    "maxValue": "",
                                    "logic": "",
                                    "child": [
                                        {
                                            "field": "",
                                            "mappingType": "",
                                            "type": "",
                                            "fieldValue": "",
                                            "minValue": "",
                                            "maxValue": "",
                                            "logic": ""
                                        }
                                    ]
                                }
                                ]
                        }
                    ];

            }



        };

        $scope.clearCondition = function(){

            $scope.logicalCondition=
                [

                ];

            localStorage.setItem('localCondition',JSON.stringify($scope.logicalCondition));
        }



        $scope.typeChange=function(valueCode,index,parentIndex){


            for(var i=0 ;i<$scope.logicalCondition[parentIndex].table.length;i++ ){
                if($scope.logicalCondition[parentIndex].table[i].field==valueCode && i!=index){
                    alert("该字段已在上面存在选择，请重新选择字段");
                    $scope.logicalCondition[parentIndex].table[index].field="";
                    return false;
                }

            }
           var status = false;
            for(var i=0;i< $scope.logicalCondition[parentIndex].table.length;i++){

                if($scope.logicalCondition[parentIndex].table[i].field == 'materialTrait') {

                  if(i!=$scope.logicalCondition[parentIndex].table.length-1) {
                      status = true;
                      var childTabile  = $scope.logicalCondition[parentIndex].table[i];
                      $scope.logicalCondition[parentIndex].table.splice(i, 1);

                      childTabile.type="子表";
                      $scope.logicalCondition[parentIndex].table.push(
                          childTabile
                      );
                  }
                }

            }



             if(!status) {

                 for (var i = 0; i < $scope.knowledgeMapping.length; i++) {
                     if ($scope.knowledgeMapping[i].paramCode == valueCode) {
                         $scope.logicalCondition[parentIndex].table[index].type = $scope.knowledgeMapping [i].controlTypes;

                     }
                 }
             }



      }


        $scope.sqlValid = function(oField)
        {
            re= /select|update|delete|exec|count|'|"|=|;|>|<|%/i;
            if ( re.test(oField) ) {
             alert("请您不要在参数中输入特殊字符和SQL关键字！");
             return false;
            }
            return true;
        }


        $scope.inputValid= function(){

            var  conditionArrayValid =  $scope.logicalCondition;
            for(var i=0;i<conditionArrayValid.length;i++){

                for(var j=0;j<conditionArrayValid[i].table.length;j++) {

                    if(conditionArrayValid[i].table[j].field=="" || conditionArrayValid[i].table[j].field==undefined){
                        alert("请补充完整条件字段");
                        return false;
                    }
                    if((conditionArrayValid[i].table[j].mappingType=="" || conditionArrayValid[i].table[j].mappingType==undefined) && conditionArrayValid[i].table[j].field!="materialTrait" && conditionArrayValid[i].table[j].type!="子表" ){
                        alert("请补充完整匹配类型");
                        return false;
                    }
                    if((conditionArrayValid[i].table[j].fieldValue=="" || conditionArrayValid[i].table[j].fieldValue==undefined) && conditionArrayValid[i].table[j].field!="materialTrait" && conditionArrayValid[i].table[j].type!="子表" ){
                        alert("请填写完整查询的值");
                        return false;
                    }

                    if((conditionArrayValid[i].table[j].logic=="" || conditionArrayValid[i].table[j].logic==undefined) && j!=0 ){
                        alert("请补充完整逻辑字段");
                        return false;
                    }

                    if( conditionArrayValid[i].table[j].field == "materialTrait"  ) {


                        for(var k=0;k<conditionArrayValid[i].table[j].child.length;k++) {
                            var btableV = conditionArrayValid[i].table[j].child[k];

                            if(btableV.field=="" || btableV.field==undefined){
                                alert("请补充完整条件字段");
                                return false;
                            }
                            if(btableV.mappingType=="" || btableV.mappingType==undefined){
                                alert("请补充完整匹配类型");
                                return false;
                            }

                            if(btableV.type=="文本框" && (btableV.fieldValue=="" || btableV.fieldValue==undefined)){
                                alert("请填写完整要查询的值");
                                return false;
                            }


                            if(btableV.type=="范围框" && (btableV.minValue=="" || btableV.minValue==undefined)){
                                alert("请填写范围值");
                                return false;
                            }

                            if(btableV.type=="范围框" &&  (btableV.maxValue=="" || btableV.maxValue==undefined)){
                                alert("请填写范围值");
                                return false;
                            }

                            if((btableV.logic=="" || btableV.logic==undefined) && k!=0){
                                alert("请补充完整逻辑字段");
                                return false;
                            }

                        }
                    }
                }

            }
            return true;
        }





       //保存sql 提交查询
        $scope.saveSqlSubmit=function(){

          if(!$scope.inputValid()){

              return false;
          }

           var  conditionArray =  $scope.logicalCondition;
           var bsql = $scope.baseSql;
           var resultSql="";

           //循环条件表格数组最外层
             for(var i=0;i<conditionArray.length;i++){
                 var whereStr = "("+bsql;
                 //循环每一组条件表格
                 for(var j=0;j<conditionArray[i].table.length;j++) {
                     if(j==0){
                         whereStr  += " and   ";
                     } else {
                         if(conditionArray[i].table[j].type != "子表" && conditionArray[i].table[j].field != "materialTrait"){



                                 whereStr += conditionArray[i].table[j].logic;


                         }
                         }
                     if ((conditionArray[i].table[j].type == "文本框" || conditionArray[i].table[j].type == "下拉框") && conditionArray[i].table[j].type != "子表" && conditionArray[i].table[j].field != "materialTrait") {

                         if (!$scope.sqlValid(conditionArray[i].table[j].fieldValue)){

                             conditionArray[i].table[j].fieldValue="";
                             //sql防注入校验
                             return false;
                         }

                         if(conditionArray[i].table[j].mappingType == "=" || conditionArray[i].table[j].mappingType == "!="){
                             whereStr += "  a." + conditionArray[i].table[j].field + "   " + conditionArray[i].table[j].mappingType + "  '" + conditionArray[i].table[j].fieldValue + "' ";
                         }else {
                             whereStr += "  a." + conditionArray[i].table[j].field + "   " + conditionArray[i].table[j].mappingType + "  '%" + conditionArray[i].table[j].fieldValue + "%' ";
                         }
                     }
                     //判断条件表格是否为子表
                     if( conditionArray[i].table[j].field == "materialTrait"  || conditionArray[i].table[j].type == "子表") {


                         //循环子表条件
                         for(var k=0;k<conditionArray[i].table[j].child.length;k++) {
                         var btable=conditionArray[i].table[j].child[k];
                         var logic="";
                         if(k==0){
                             if(j==0){
                                 logic=" ";
                             }else {
                                 logic = conditionArray[i].table[j].logic;
                             }
                         }else{

                                 logic = conditionArray[i].table[j].child[k].logic;

                             }

                             if (btable.type == "文本框" || btable.type == "下拉框") {

                                 if (!$scope.sqlValid(btable.fieldValue)){
                                     conditionArray[i].table[j].child[k].fieldValue="";
                                     //sql防注入校验
                                     return false;
                                 }

                                 whereStr  += "  "+logic+"   ( c.paramName = '"+btable.field+"' and  c.paramAttribute "+ btable.mappingType+" ";
                                 whereStr +="  '%"+btable.fieldValue+"%' )";
                             }
                             if ( btable.type == "范围框" &&  btable.mappingType=="like") {

                                 if (!$scope.sqlValid(btable.maxValue)){
                                     conditionArray[i].table[j].child[k].maxValue="";
                                     //sql防注入校验
                                     return false;
                                 }

                                 if (!$scope.sqlValid(btable.minValue)){
                                     conditionArray[i].table[j].child[k].minValue="";
                                     //sql防注入校验
                                     return false;
                                 }


                                 whereStr  += "  "+logic+"  ( c.paramName = '"+btable.field+"' ";
                                 whereStr +="  and     c.paramMin  <= "+btable.minValue+" and  c.paramMax > "+btable.maxValue+"  )";
                             }else if(btable.type == "范围框" &&  btable.mappingType=="not like"){

                                 if (!$scope.sqlValid(btable.maxValue)){
                                     conditionArray[i].table[j].child[k].maxValue="";
                                     //sql防注入校验
                                     return false;
                                 }

                                 if (!$scope.sqlValid(btable.minValue)){
                                     conditionArray[i].table[j].child[k].minValue="";
                                     //sql防注入校验
                                     return false;
                                 }

                                 whereStr  += "  "+logic+"  ( c.paramName = '"+btable.field+"' and  a.documentName  not in  " ;
                                 whereStr += "( " +
                                     "select  distinct "+" a.documentName "+"  from i_knowledge a INNER JOIN ot_instancecontext b on a.ObjectID = b.BizObjectId left join i_materialtrait c on c.ParentObjectID=a.ObjectID  where 1=1 "
                                     +" and "+" ( c.paramName = '"+btable.field+"'  and  c.paramMin <= "+btable.minValue+"  and   c.paramMax > "+btable.maxValue +" )  and  a.nowState=0) )";
                             }
                         }
                     }

                     }
                 whereStr = whereStr+" and  a.nowState=0 ) ";
                 if(i!=conditionArray.length-1 && conditionArray.length>1) {
                     resultSql += whereStr + " " + conditionArray[Number(i)+1].andOr + " ";
                 }else{
                     resultSql += whereStr + " "
                 }
                 }

             localStorage.setItem('localCondition',JSON.stringify(conditionArray));

            var base = new Base64();
            var resultSqlEncode = base.encode(resultSql);
            localStorage.setItem('sqlStr',resultSqlEncode);
            location.href="/Portal/#/app/knowledgePlatform/kumhosunny/knowledge?searchSql=true";

        }



        $scope.typeChildChange=function(valueCode,index,parentIndex,pindex) {
            for(var i=0 ;i<$scope.logicalCondition[parentIndex].table[pindex].child.length;i++ ){
                if($scope.logicalCondition[parentIndex].table[pindex].child[i].field==valueCode && i!=index){
                    alert("该字段已在上面存在选择，请重新选择字段");
                    $scope.logicalCondition[parentIndex].table[pindex].child[index].field="";
                    return false;
                }
            }
            for(var i=0 ;i<$scope.knowledgeChildMapping.length;i++ ){
                if($scope.knowledgeChildMapping[i].paramName == valueCode ){
                    $scope.logicalCondition[parentIndex].table[pindex].child[index].type=$scope.knowledgeChildMapping[i].controlTypes;


                }
            }

        }


        $scope.addTableCondition=function() {
            $scope.logicalCondition.push(  {
                "andOr":"UNION",
                "table":
                    [
                        {
                            "field": "",
                            "mappingType": "",
                            "type": "",
                            "fieldValue": "",
                            "minValue": "",
                            "maxValue": "",
                            "logic": "",
                            "child": [
                                {
                                    "field": "",
                                    "mappingType": "",
                                    "type": "",
                                    "fieldValue": "",
                                    "minValue": "",
                                    "maxValue": "",
                                    "logic": ""
                                }
                            ]
                        }
                    ]
            });


        }


        $scope.addParentRow=function(index) {

            $scope.logicalCondition[index].table.push( {
                "field":"",
                "mappingType":"",
                "type":"",
                "fieldValue":"",
                "minValue":"",
                "maxValue":"",
                "logic":"",
                "child":[
                    {
                        "field":"",
                        "mappingType":"",
                        "type":"",
                        "fieldValue":"",
                        "minValue":"",
                        "maxValue":"",
                        "logic":""
                    }
                ]
            });
            for(var i=0;i< $scope.logicalCondition[index].table.length;i++){

                if($scope.logicalCondition[index].table[i].field == 'materialTrait') {
                    status= true;
                    var childTabile = $scope.logicalCondition[index].table[i];
                    $scope.logicalCondition[index].table.splice(i, 1);
                    childTabile.type="子表";
                    $scope.logicalCondition[index].table.push (
                        childTabile
                    );

                }

            }



        }

        $scope.addChildRow=function(tindex,pindex){
            $scope.logicalCondition[tindex].table[pindex].child.push( {
                "field":"",
                "mappingType":"",
                "type":"",
                "fieldValue":"",
                "minValue":"",
                "maxValue":"",
                "logic":""

            });


        }


        $scope.removeParentTable=function(index){
            var msg = "将删除本表格下所有条件,您确定要删除吗？\n\n请确认！";
            if (confirm(msg)==true) {
                $scope.logicalCondition.splice(index, 1);
            }else{
                return false;
            }
        }

        $scope.removeParentRow =function(index,tindex){

            $scope.logicalCondition[tindex].table.splice(index, 1);
        }

        $scope.removeChildRow =function(index,tindex,pindex){

            $scope.logicalCondition[tindex].table[pindex].child.splice(index, 1);
        }









    }]);